class LIst {
  //构造函数
  constructor() {
    this.getData(1);
    this.lazyF()
    window.onload = this.kK()
  }
  kK() {
    this.oncK()

  }

  //绑定事件函数
  oncK() {
    //给左按钮绑定个点击事件
    this.$('.pn-prev').onclick = this.zuoL.bind(this)
    //给右箭头绑定一个点击事件
    this.$('.pn-next').onclick = this.youR.bind(this)
    //小列表绑定点击事件  事件委托
    this.$('.sk_list').addEventListener('click', this.lisObj.bind(this))
    //懒加载  给window绑定滑轮事件
    window.addEventListener('scroll', this.onS.bind(this))
    // window.onscroll = this.onS()
    //  window.addEventListener('scroll', this.onS.bind(this))
  }
  onS() {
    let imgA = [...this.$('.sk_goods img')]
    let mi = imgA.length
    this.lazyF(imgA, mi)
  }

  //懒加载函数
  lazyF(imgA, length) {
    // console.log(length);
    //循环遍历所有的照片获取他们的值
    for (let i = 0; i < length; i++) {
      //console.log(imgA[i]);
      //获取元素到文档顶部的距离 
      let imgT = [...this.$('.sk_goods a img')][i].getBoundingClientRect().top
      //获取浏览器可视区的高度
      let widH = window.innerHeight
      //获取DOM文档被卷上去的内容高
      let scrT = document.documentElement.scrollTop
      // console.log(imgT, widH, scrT);
      if (imgT - scrT <= widH) {
        setTimeout(() => { imgA[i].src = imgA[i].dataset.src }, 1000
        )

      }
    }

  }

  //小列表回调函数  4个小LLLLLL换页
  lisObj(eve) {
    //发送请求
    let num = Math.floor(Math.random() * 50)
    let param = this.newIndex + num
    //获取事件源
    let res = eve.target
    if (res.nodeName != 'A') return;
    document.querySelector('.sk_list .current').className = ''
    res.parentNode.className = 'current'
    let resS = document.createElement('div')
    resS.className = 'sk_bd'
    document.querySelector('#sS').id = ''
    resS.id = 'sS'
    this.$('.sk_container').prepend(resS)

    // document.querySelector('.sk_bd').className = ''
    axios.get('http://localhost:8888/goods/list?current=' + param)
      .then(function (response) {
        let { data, status } = response
        let html = '';
        data.list.forEach(good => {
          // console.log(good);

          html += `<ul><li class="sk_goods">
    <a href = "detail.html" ><img src="./images/black.gif" data-src="${good.img_big_logo}"></a>
      <h5 class="sk_goods_title">${good.title}</h5>
      <p class="sk_goods_price"><em>¥${good.current_price}</em> <del>￥${good.price}</del></p>
      <div class="sk_goods_progress">
          已售<i>${good.sale_type}</i>
          <div class="bar">
              <div class="bar_in"></div>
          </div>
          剩余<em>${good.goods_number}</em>件
      </div>
      <a href="#" class="sk_goods_buy" onclick='LIst.nowBuy(${good.goods_id})'>立即抢购</a>
  </li ></ul> `
        })
        document.querySelector('.sk_bd').innerHTML = html
      })
  }








  //循环给span下面的a绑定点击事件
  xunH(res) {
    // console.log(res);
    this.$('.page_num .aA').forEach((v, k) => {
      //console.log(v, k);
      this.$('.page_num .aA')[k].onclick = this.xunHko.bind(this, k, res)
    })
  }

  //定义两个变量
  newIndex = 0;
  oldIndex = 0;
  xunHko(k, res) {
    let { data } = res
    let msg = data.yourParams
    //获取参数
    let { current, pagesize } = msg
    //console.log(current, pagesize);
    this.oldIndex = this.newIndex
    this.newIndex = k
    //定义一个变量参数
    let param = this.newIndex + 1
    // console.log(param);
    this.getData(param)

    document.querySelector('.page_num .current').className = 'aA'
    this.$('.page_num .aA')[this.newIndex].className = 'aA current'
    //发送请求
    // axios.get('http://localhost:8888/goods/list?current=' + param)
    //   .then(function (response) {
    //     let { data, status } = response
    //     let html = '';
    //     data.list.forEach(good => {
    //       // console.log(good);
    //       html += `<li class="sk_goods">
    //   <a href = "detail.html" ><img src="${good.img_big_logo}"></a>
    //     <h5 class="sk_goods_title">${good.title}</h5>
    //     <p class="sk_goods_price"><em>¥${good.current_price}</em> <del>￥${good.price}</del></p>
    //     <div class="sk_goods_progress">
    //         已售<i>${good.sale_type}</i>
    //         <div class="bar">
    //             <div class="bar_in"></div>
    //         </div>
    //         剩余<em>${good.goods_number}</em>件
    //     </div>
    //     <a href="#" class="sk_goods_buy" onclick='LIst.nowBuy(${good.goods_id})'>立即抢购</a>
    // </li > `
    //     })
    //     document.querySelector('.sk_bd ul').innerHTML = html
    //   })
  }

  //左按钮的回调函数
  zuoL() {
    this.oldIndex = this.newIndex
    if (this.newIndex == 0) {
      this.newIndex == 1
    } else {
      this.newIndex--
    }
    let param = this.newIndex + 1
    this.getData(param)
    document.querySelector('.page_num .current').className = 'aA'
    this.$('.page_num .aA')[this.newIndex].className = 'aA current'
  }
  //右箭头的回调函数
  youR() {
    this.oldIndex = this.newIndex;
    if (this.newIndex == this.$('.page_num .current').length - 1) {
      this.newIndex = 0
    } else {
      this.newIndex++
    }
    let param = this.newIndex + 1
    this.getData(param)
    if (param > 5) {
      this.$('.dotted').innerHTML = `<a href="#" class="aA zZ">${param}</a>`
    }
    document.querySelector('.page_num .current').className = 'aA'
    this.$('.page_num .aA')[this.newIndex].className = 'aA current'
  }

  //发送请求 获取商品信息
  async getData(param) {
    // console.log(param);
    let res = await axios.get('http://localhost:8888/goods/list?current=' + param)
    //console.log(res);
    //获取到返回值
    this.xunH(res)

    //解构赋值获取商品信息
    let { data, status } = res
    let info = data.info
    //console.log(data);
    //判断是否请求成功
    if (status != 200 || data.code != 1) return
    let html = '';
    data.list.forEach(good => {
      //console.log(good);
      html += `<ul> <li class="sk_goods">
    <a href = "detail.html" ><img src="./images/black.gif" data-src="${good.img_big_logo}"></a>
        <h5 class="sk_goods_title">${good.title}</h5>
        <p class="sk_goods_price"><em>¥${good.current_price}</em> <del>￥${good.price}</del></p>
        <div class="sk_goods_progress">
            已售<i>${good.sale_type}</i>
            <div class="bar">
                <div class="bar_in"></div>
            </div>
            剩余<em>${good.goods_number}</em>件
        </div>
        <a href="#" class="sk_goods_buy" onclick='LIst.nowBuy(${good.goods_id})'>立即抢购</a>
    </li > </ul>`;

    })

    // console.log(html);
    // console.log(this.$('.sk_bd'));
    // console.log(this);
    document.querySelector('.sk_bd').innerHTML = html
    document.querySelector('.page_skip').innerHTML = `
                 共${data.total}页 到第
                <input type="text"> 页
                <button>确定</button>
                `

  }

  //给立即购买绑定点击事件
  static nowBuy(goods) {
    // console.log(11111);
    //获取token值
    let token = localStorage.getItem('token')
    //判断是否登录了
    if (!token) location.href = './login.html'
    //console.log(res);
    //将用户ID和商品id获取过来
    let userid = localStorage.getItem('user_Id')
    let goods_id = goods;
    console.log(userid, goods_id);
    //设置参数将用户ID和商品ID拼接
    let param = `id=${userid}&goodsId=${goods_id}`
    //添加到购物车 
    //axios请求头设置
    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    //token认证编码设置
    axios.defaults.headers.common['Authorization'] = token;
    //发送请求
    axios.post('http://localhost:8888/cart/add', param)
      .then(function (res) {
        //判断是否登录了
        let { data, status } = res;
        if (status != 200) return;
        if (data.code == 0) location.href = "./login.html"
        console.log(res);
        //提示信息框确认下一步操作

        layer.confirm('是否去购物车结算', {
          btn: ['是', '继续买'] //按钮
        }, function () {
          // layer.msg('的确很重要', { icon: 1 });
          // 去购物车
          location.href = './cart.html';
        });
      })
  }
  //获取DOM节点
  $(ele) {
    let jie = document.querySelectorAll(ele)
    return jie.length == 1 ? jie[0] : jie
  }
}
new LIst()